<script setup>

import {onMounted, reactive, ref} from "vue";
import {RULE} from "../../../const/index.js";
import {ElMessage} from "element-plus";
import router from "../../../router/index.js";
import MyNav from "../../../components/MyNav.vue";
import {listApi, updateApi} from "../../../api/axios.js";
import MyForm from "../../../components/MyForm.vue";
import {getResponseData} from "../../../request/index.js";

// 部门记录
let dept = JSON.parse(sessionStorage.getItem('row'));
// 所属部门下拉菜单选项
let deptOptions = ref([]);

// 路径导航
const navItems = [
  {icon: 'Avatar', label: '用户管理', url: '/Dept'},
  {icon: 'HomeFilled', label: '部门列表', url: '/Dept'},
  {icon: 'Edit', label: '修改房间'},
];

//  表单项 + 表单值 + 表单规则
let items = ref([
  {label: '部门名称', prop: 'title', required: true, span: 12},
  {span: 12, hidden: true},
  {label: '所在房间', prop: 'fkRoomId', required: true, type: 'select', options: deptOptions.value, span: 12},
  {label: '部门描述', prop: 'info', type: 'textarea'},
]);
let params = reactive(dept);
let rules = {title: RULE.TITLE, info: RULE.INFO};

/* ================= 修改成功后 ================= */
function updateSuccess() {
  ElMessage.success('修改记录成功');
  setTimeout(() => router.push('/Dept'), 1000);
}

/* ================= 加载函数 ================= */
onMounted(async () => {
  // 查询全部房间并添加到下拉菜单选项中
  Object.values(getResponseData(await listApi({module: 'room'}))).forEach(dept => {
    deptOptions.value.push({label: dept['title'], value: dept['id']})
  });
});

</script>

<template>
  <my-nav :items="navItems"/>
  <el-card v-if="deptOptions.length > 0" class="dept-update-card" header="修改部门">
    <my-form type="update"
             :items="items"
             :params="params"
             :rules="rules"
             :api="updateApi"
             :args="{module: 'dept'}"
             :callback="updateSuccess"/>
  </el-card>
</template>

<style scoped lang="scss">
.dept-update-card {
  width: 60%;
  margin: 65px auto 0;
}
</style>